import entryStore from '@/store/entry';
import { createStoreBindings } from '@/miniprogram_npm/mobx-miniprogram-bindings/index';

import tools from '@/utils/tools';
import { getEntries } from '@/service/api/entry';

import Message from 'tdesign-miniprogram/message/index';
const messageDefaultConfig = (content) => {
    return {
        context: this,
        offset: [60, 32],
        content: content
    };
};

Page({
    data: {
        briefText: '',
        entries: [],
        popupShow: false
    },

    onLoad() {
        this.storeBindings = createStoreBindings(this, {
            store: entryStore,
            fields: ['entryLoaded'],
            actions: ['setEntries', 'getEntryByTitle', 'getOrdinaryEntries']
        });
    },

    onUnload() {
        this.storeBindings.destroyStoreBindings();
    },

    async onReady() {
        try {
            if (!this.data.entryLoaded) {
                await getEntries();
            }
            const briefIntro = this.getEntryByTitle('简介');
            const ordinaryEntries = this.getOrdinaryEntries();
            this.setData({
                briefText: briefIntro.content,
                entries: ordinaryEntries
            });
        } catch (err) {
            Message.error(messageDefaultConfig(err.message || '请求失败'));
        }
    },

    onPullDownRefresh: tools.throttle(async function () {
        try {
            await getEntries();
            const briefIntro = this.getEntryByTitle('简介');
            const ordinaryEntries = this.getOrdinaryEntries();
            this.setData({
                briefText: briefIntro.content,
                entries: ordinaryEntries
            });
        } catch (err) {
            Message.error(messageDefaultConfig(err.message || '请求失败'));
        }
    }, 10000),

    goDetail() {
        this.setData({
            popupShow: true
        });
    },

    onVisibleChange(e) {
        this.setData({
            popupShow: e.detail.visible
        });
    }
});
